/**
 * Created by lianpeng on 2014/11/24.
 */
var express = require('express');
var router = express.Router();
var Consts = require('./consts');
var resultJson = require('./result-json');
var User = require('./models/User');
var Utils = require('./utils');
var cookie = require('cookie');
var logger = require("./models/logger")
var url = require("url");

router.post("/*", function(req, res, next) {
    var pathname = url.parse(req.url).pathname.toString();
    console.log("path => ", req.cookies, pathname);
    if (pathname != "/user/lgn" && pathname != "/user/reg" &&
        pathname != "/user/findPwd" && pathname != "/user/" &&
        pathname != "/user/resetPassword" &&
        pathname != "/user/confirmation" &&
        pathname != "/listHome" &&
        pathname != "/course/list" &&
        pathname != "/project/list" &&
        pathname != "/comment/list" &&
        pathname != "/message/newmsg" &&
        pathname != "/project/detail" &&
        pathname != "/direction/list" &&
        pathname != "/direction/listCourseOrProject" &&
        pathname != "/direction/listCourse" &&
        pathname != "/direction/listProject" &&
        pathname != "/broadcast/list" &&
        pathname != "/broadcast/detail" &&
        pathname != "/course/detail" &&
        pathname != "/teacher/detail") {
        if (req.cookies[Consts.COOKIE.COOKIE_CODE] != "") {
            User.findOne({
                "token": req.cookies[Consts.COOKIE.COOKIE_CODE],
                "status": Consts.STATUS.NORMAL
            }, {
                "_id": 1,
                "name": 1,
                "type": 1,
                "status": 1,
                "token": 1,
                course: 1
            }, function(err, user) {
                if (err) {
                    logger.error(err, "提取用户身份错误：");
                    return res.send(resultJson(2));
                }
                if (user && user.token == req.cookies[Consts.COOKIE.COOKIE_CODE]) {
                    var cookies = [cookie.serialize(Consts.COOKIE.COOKIE_CODE, req.cookies[Consts.COOKIE.COOKIE_CODE], {
                        maxAge: Consts.COOKIE.MAXAGE,
                        path: "/"
                    })];
                    // 设置用户信息
                    req.body._user = user;
                    res.setHeader("Set-cookie", cookies);
                    next();
                } else
                    res.send(resultJson(4));
            })
        } else
            res.send(resultJson(6));
    } else {
        req.body._user = {};
        next();
    }
})

module.exports = router;